import React, { useEffect, useState, useRef, useImperativeHandle } from 'react';
import { Tabs, Row, Col, Form, message } from 'antd';
import { connect } from 'umi';
import { cloneDeep, size } from 'lodash';
import { ReactSortable } from 'react-sortablejs';
// import lookforward from '@/assets/lookforward.png';
import DraggableItem from './components/DraggableItem/DraggableItem';
import RightPanel from './components/RightPanel';
import { baseControlConfig, customControlConfig } from './formConfig';
// import {
//     getDrawingList
// } from './utils/db';

import styles from './index.less';

const { TabPane } = Tabs;

const IconFont = ({ icon = 'iconprocess_common_textfield_icon' }) => <i className={`iconfont ${icon}`}></i>;

const FormControls = React.forwardRef(({ location, workFlowModel, dispatch, tabName }, ref) => {
    const { operation } = location.query;
    const { formItemList, processConditions } = workFlowModel;
    // const drawingListInDB = getDrawingList();
    const [commonComponentList, setCommonComponentLis] = useState(baseControlConfig);

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const [customMadeComponentList, setCustomMadeComponentList] = useState(customControlConfig);
    const [activeData, setActiveData] = useState(null);
    const [listCenter, setListCenter] = useState([]);
    const [initFlag, setInitFlag] = useState(false); // 初始化标志
    const [sortIndex, setSortIndex] = useState(-1);
    const [errArr, setErrArr] = useState([]);

    // 编辑态
    const [editing, setEditing] = useState(false);
    const callback = () => {};

    // 初始化formItem项
    const initEditItemList = () => {
        setListCenter(formItemList);
        setInitFlag(true);
    };
    // 选中的值
    const handleSelect = value => {
        if (value) {
            setActiveData(value);
        }
    };
    const handleDelete = value => {
        if (value.isUsed) {
            message.error('已作为条件不可删除！');
            return;
        }

        // 如果删除的组件在删除错误数组中就删除
        const delErrArrID = errArr.findIndex(item => item.formId === value.formId);
        if (delErrArrID > -1) {
            setErrArr(errArr.slice(delErrArrID, 0));
        }

        const newData = listCenter.filter(item => item.formId !== value.formId);
        // 当前选中的值缓存起来
        setListCenter(newData);
        let result = {};
        // 判断是否当前有选中的值
        if (activeData) {
            if (value.formId !== activeData.formId) {
                result = activeData;
            }
            setActiveData(result);
        }
        dispatch({ type: 'workFlowModel/updateFormItemList', payload: newData });

        // 更新条件数组
        dispatch({
            type: 'workFlowModel/delPCondition',
            payload: value
        });
    };

    // 右侧表单的ref
    const rightPanelRef = useRef();
    const resetRightForm = () => {
        rightPanelRef.current.resetFields();
    };

    const renderIcon = item => {
        const icon = item.tagIcon || 'iconprocess_common_textfield_icon';
        return <IconFont icon={icon} />;
    };

    // 提交发布的验证
    useImperativeHandle(ref, () => ({
        handleUpdate: typeString =>
            new Promise((resolve, reject) => {
                if (typeString === 'hold') {
                    resolve({ formData: listCenter });
                } else if (listCenter.length === 0) {
                    // eslint-disable-next-line prefer-promise-reject-errors
                    reject({ tabName, message: '请先添加表单控件' });
                } else if (errArr.length > 0) {
                    // eslint-disable-next-line prefer-promise-reject-errors
                    reject({ tabName, message: `${errArr.map(item => item.label).join(',')} 有属性错误` });
                } else {
                    resolve({ formData: listCenter });
                }
            })
    }));

    useEffect(() => {
        // 兼容火狐拖拽搜索问题
        document.body.ondrop = event => {
            event.preventDefault();
            event.stopPropagation();
        };
    }, []);

    useEffect(() => {
        dispatch({ type: 'workFlowModel/updateFormItemList', payload: listCenter });

        // 更新当前选中组件是否使用的属性
        if (activeData) {
            const obj = listCenter.find(item => item.formId === activeData.formId);
            setActiveData({ ...activeData, isUsed: obj?.isUsed });
        }
    }, [listCenter]);

    useEffect(() => {
        if (!initFlag && formItemList && formItemList.length > 0 && operation === 'edit') {
            initEditItemList();
        }
    }, [formItemList]);

    // 流程使用条件后联动
    useEffect(() => {
        if (size(processConditions) > 0 && size(listCenter) > 0) {
            const arr = cloneDeep(listCenter);
            arr.map(item => {
                const obj = item;
                obj.isUsed = false;
                const isHas = processConditions.find(subItem => subItem.formId === item.formId);
                if (isHas) {
                    obj.isUsed = isHas.isUsed;
                }
                return obj;
            });
            setListCenter(arr);
        }
    }, [processConditions]);

    return (
        <div className={styles.formCtr}>
            <Row>
                <Col span={6}>
                    <Tabs defaultActiveKey="1" onChange={callback}>
                        <TabPane tab="常用组件" key="1">
                            <div className={styles.componentsList}>
                                <ReactSortable
                                    list={commonComponentList}
                                    setList={setCommonComponentLis}
                                    sort={false}
                                    group={{ name: 'disable-group-name', pull: 'clone', put: false }}
                                    clone={item => ({ ...item })}
                                >
                                    {commonComponentList.map(item => (
                                        <div
                                            className={styles.componentsItem}
                                            key={item.label}
                                            onMouseDown={() => setEditing(false)}
                                        >
                                            <div className={styles.componentsBody}>
                                                {item.label}
                                                {renderIcon(item)}
                                            </div>
                                        </div>
                                    ))}
                                </ReactSortable>
                            </div>
                        </TabPane>
                        <TabPane tab="套件" key="2">
                            {/* <div className={styles.emptyCtr}>
                                <img src={lookforward} alt=""/>
                                <span>敬请期待...</span>
                            </div> */}
                            <div className={styles.componentsList}>
                                <ReactSortable
                                    key={listCenter.length}
                                    disabled={listCenter.findIndex(item => item.cmpType === 'custom') > -1}
                                    list={customMadeComponentList}
                                    setList={setCustomMadeComponentList}
                                    sort={false}
                                    // animation={150}
                                    group={{ name: 'disable-group-name', pull: 'clone' }}
                                >
                                    {customMadeComponentList.map(item => (
                                        <div
                                            className={styles.componentsItem}
                                            key={item.label}
                                            onMouseDown={() => setEditing(false)}
                                        >
                                            <div className={styles.componentsBody}>
                                                {item.label}
                                                {renderIcon(item)}
                                            </div>
                                        </div>
                                    ))}
                                </ReactSortable>
                            </div>
                        </TabPane>
                    </Tabs>
                </Col>
                <Col span={12}>
                    <div className={styles.draggableBox}>
                        <div className={styles.formCtr}>
                            <div className={styles.outeripad}>
                                <div className={styles.ipadbody}>
                                    <div className={styles.ipadscreen}>
                                        <DraggableItem
                                            activeData={activeData}
                                            setActiveData={setActiveData}
                                            onSelect={handleSelect}
                                            onDelete={handleDelete}
                                            listCenter={listCenter}
                                            setListCenter={setListCenter}
                                            dispatch={dispatch}
                                            resetRightForm={resetRightForm}
                                            sortIndex={sortIndex}
                                            setSortIndex={setSortIndex}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </Col>
                <Col span={6}>
                    <RightPanel
                        cRef={rightPanelRef}
                        activeData={activeData}
                        onSelect={handleSelect}
                        listCenter={listCenter}
                        setListCenter={setListCenter}
                        editing={editing}
                        setEditing={setEditing}
                        errArr={errArr}
                        setErrArr={setErrArr}
                    />
                </Col>
            </Row>
        </div>
    );
});

export default connect(({ workFlowModel }) => ({
    workFlowModel
}))(Form.create()(FormControls));
